package com.lznAdmin.system.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.lznAdmin.base.common.util.RedisUtil;
import com.lznAdmin.base.lznAdminResult;
import com.lznAdmin.system.entity.SysPermission;
import com.lznAdmin.system.entity.SysUser;
import com.lznAdmin.system.service.SysUserService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.Principal;
import java.util.List;
import java.util.Map;

/**
 * @program: lzn-manage-parent
 * @description: 登录界面及验证码
 * @author: lzn
 * @create: 2021-07-27 01:48
 **/
// @CrossOrigin(value = "http://localhost:8000")
@Slf4j
@RestController
public class CustomLoginController {
    public static final String SESSION_KEY = "SESSION_KEY_IMAGE_CODE";
    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    SysUserService sysUserService;


    @RequestMapping({"/login"})
    public String toLogin() {
        return "login";
    }


    /**
     * 图片验证码
     */
    @GetMapping("/code/image")
    public lznAdminResult captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String key = UUID.randomUUID().toString();
        String code = defaultKaptcha.createText();

        BufferedImage image = defaultKaptcha.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);

        BASE64Encoder encoder = new BASE64Encoder();
        String str = "data:image/jpeg;base64,";
        String base64Img = str + encoder.encode(outputStream.toByteArray());

        boolean hset = redisUtil.hset("captcha", key, code, 120);
        log.info("生成的图形验证码是:" + code + "------" + "生成的key:" + key);
        return lznAdminResult.ok(MapUtil.builder()
                .put("token", key)
                .put("captchaImg", base64Img)
                .build());
    }

    /**
     * 获取用户信息接口
     *
     * @param principal
     * @return
     */
    @ApiOperation(value = "Principal", notes = "userInfo")
    @GetMapping("/user/info")
    public lznAdminResult userInfo(Principal principal) {

        SysUser sysUser = sysUserService.findByUsername(principal.getName());
        log.info("getUserPermissions");
        List<SysPermission> userPermissions = sysUserService.getUserPermissions(sysUser.getId());
        log.info("userinfo: " + sysUser);
        log.info("userPermissions: " + userPermissions);
        Map<Object, Object> permissions = MapUtil.builder()
                .put("permissions", userPermissions)
                .map();
        System.out.println(permissions.toString());
        return lznAdminResult.ok(MapUtil.builder()
                .put("id", sysUser.getId())
                .put("name", sysUser.getNickName())
                .put("username", sysUser.getUsername())
                .put("avatar", sysUser.getAvatar())
                .put("createTime", DateUtil.formatDateTime(sysUser.getCreateDate()))
                .put("role", permissions)
                .map()
        );
    }


    /**
     * 获取系统菜单信息
     *
     * @param principal
     * @return
     */
    @ApiOperation(value = "Principal", notes = "userInfo")
    @GetMapping("/user/nav")
    public lznAdminResult getUserNav(Principal principal) {
        SysUser sysUser = sysUserService.findByUsername(principal.getName());
        List<SysPermission> userPermissions = sysUserService.getUserPermissions(sysUser.getId());
        return lznAdminResult.ok(userPermissions);
    }
}
